<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";



class NewsLetter extends IPlugin 
{
    var $color;
    var $from_email;
    
    function NewsLetter($parent = null)
    {
        $core = getCoreInstance();
        $this->from_email= $core->config['system']['info_email'];
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
    }
    
    function getPluginTag() { return "newsletter"; }
    function getPluginName() { return "Newsletter Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    function getFromEmail() { return $this->from_email; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuTitle" : { return "Newsletter"; } break;
        };
        return $result;
    }

    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------
    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
        
        $arg = getCoreInstance();
        $arg = $arg->getGET();
        
        if("echo" == $arg["action"])
        {
            echo "CustomerList: echo: ".$arg["string"];
        }
        
        if("doSubmitSubscriber" == $_POST["action"])
        {
            $z = $_POST;
            $uid = $z["id"];
            unset($z["action"], $z["id"]);
            
            $sql = "";
            foreach ($z as $k => $v)
            {
                $sql .= ($sql=="" ? "" : ", ")."{$k} = '".str2db($v)."'";
            }
            
            $core = getCoreInstance();
            $db = $core->getProperty("db");
            
            $sql = "update mail_templates set {$sql} where id={$uid}";
            $db->Exec($sql);
        }elseif ("doAddNewsletter" == $_POST['action'])
        {
            $z = $_POST;
            unset($z["action"]);
            
            $keys = "";
            $vars = "";
            foreach ($z as $k => $v)
            {
                $keys .=($keys=="" ? "" : ", ")."{$k}";
                $vars .=($vars=="" ? "" : ", ")."'".str2db($v)."'";
            }
            
            $core = getCoreInstance();
            $db = $core->getProperty("db");
            
            $sql = "insert into mail_templates ({$keys}) values ({$vars})";
            $db->Exec($sql);
        }elseif ("doActionSend" == $_POST['action'])
        {
            $z = $_POST;
            unset($z["action"]);
            $template_id = $_POST['template'];
            
            $core = getCoreInstance();
            $db = $core->getProperty("db");
            $sql = "select subject,content from mail_templates where id='".str2db($template_id)."'";
            $mail_data = $db->getAll($sql);
            $mail_content = db2str($mail_data[0]['content']);
            $mail_subject = db2str($mail_data[0]['subject']);
            
        //----- smtp authrize
                  //  $mail->SMTPAuth = true;
                  //  $mail->Username = "";
                  //  $mail->Password = "";
        //----------- /
            
     // ---------------- get mail_to  SUBSCRIBERS & Clients "by name"
        // debug($_POST);
            if (isset($_POST[send_all])) 
            {
                $q_subscriber="select concat('subscribe|',id) as id, concat(fname,' ',lname) as name,email from subscribe";
                $q_client="select concat('client|',client_id) as id, client_name as name, client_email as email from clients where client_name != 'noone' and client_name != 'Administrator'";
                $receivers_by_name=array_merge($db->getAll($q_subscriber,0),$db->getAll($q_client,0));
            }
            else 
            {
                if (count($_POST['receivers']))
                {
                    $to_subscriber="''";
                    $to_client="''";
                    foreach ($_POST['receivers'] as $v)
                    {
                        list($receiver,$id) = explode("|",$v);
                        if ($receiver=="subscriber") $to_subscriber.=",".$id;
                        if ($receiver=="client") $to_client.=",".$id;
                    } 
                    $q_subscriber="select concat('subscribe|',id) as id, concat(fname,' ',lname) as name,email from subscribe where id in ($to_subscriber)";
                    $q_client="select concat('client|',client_id) as id, client_name as name, client_email as email from clients where client_id in ($to_client)";
                    $receivers_by_name=array_merge($db->getAll($q_subscriber,0),$db->getAll($q_client,0));
                    //debug($receivers_by_name,"name");                
                }
        // ---------------- get mail_to  SUBSCRIBERS & Clients "by mail group"
                 if (count($_POST['mail_groups']))
                {
                    $sub_sql_where="";
                    foreach ($_POST['mail_groups'] as $v)
                    {
                        if ($sub_sql_where) $sub_sql_where.=" or ";
                        $sub_sql_where.=" mail_groups like '%<$v>%'";
                    } 
                    $q_subscriber_mail_groups="select concat('subscribe|',id) as id, concat(fname,' ',lname) as name,email from subscribe where $sub_sql_where";
                    $q_client_mail_groups="select  concat('client|',client_id) as id,  client_name as name, client_email as email from clients where ($sub_sql_where)  and client_name != 'noone' and client_name != 'Administrator'";
                    
                    $receivers_by_group=array_merge($db->getAll($q_subscriber_mail_groups,0),$db->getAll($q_client_mail_groups,0));
                    //debug($receivers_by_group,"group");
                }
            }    
            // - merge union whithout repeat
            $receivers=array_merge($receivers_by_name,$receivers_by_group);
            for ($i=0; $i<count($receivers); $i++) {$receivers[$i]=implode("|=|", $receivers[$i]);}
            $receivers=array_unique($receivers);
            //for ($i=0; $i<count($receivers); $i++) {list($receivers1[$i][name],$receivers1[$i][email])=explode("|=|", $receivers[$i]);}
            $i=0;
            foreach ($receivers as $v) {list($id,$name,$email)=explode("|=|", $v); $receivers_ok[]=array("id" => $id, "name" => $name, "email" => $email);}
            $receivers=$receivers_ok;
            //debug($receivers);
        // ---------------- / get mail_to

            // -------- init MAILER (MIME)
            $html = preg_replace('/src="[\s]*http:/', 'src_skip="http:', $mail_content); //
            $html = preg_replace('/src="..\/..\/../', 'src="', $html);           //
            //$html = preg_replace('/(src=")([^\\"]*(?<=\/))/', '\1', $html);
            $html = preg_replace('/src="/', 'src="'.$cfg["system"]["http_root"], $html);
            $html = preg_replace('/src_skip="http:/', 'src="http:', $html);      //
            $mail = new PHPMailer();
            $mail->Host     = $core->config["system"]["mail_host"]; // SMTP servers
            //debug($mail->Host);
            $mail->From     = $core->config["system"]["mail_info"];
            //debug($mail->From);
            $mail->FromName = "Info center of the ".$core->config["system"]["mail_info"];
            $mail->IsHTML(true);                               // send as HTML
            $mail->Subject  =  $mail_subject;
            // -------- / init MAILER (MIME)            
           
                // ------------------- merge CSS for FCKeditor
                $filename="../../mailer/mail_fck_css.php";
                //debug($filename);
                $fd = fopen ($filename, "rb");
                $content_css = fread ($fd, filesize ($filename));
                fclose ($fd);
                 // ------------------- merge CSS for FCKeditor                
                 //debug($receivers);
                 
                 // for mail statistic by letter -------
                 $max_id_grouping=$db->getone("select max(id_grouping) from mail_statistics");
                 if ($max_id_grouping=="") $max_id_grouping=0;
                 $max_id_grouping=$max_id_grouping+1;
                 $now=date("Y-m-d H:i:s");
                 /// -------------------------------------- 
                 
        for ($i=0; $i<count($receivers); $i++)
        {
                $html1 = preg_replace('/%NAME%/', $receivers[$i]["name"], $html);
                $html2 = preg_replace('/%EMAIL%/', $receivers[$i]["email"], $html1);
                $html3=$content_css."\n".$html2;
                $html3=str_replace("<img","\r\n<img",$html3);
                //$html3=str_replace("\r\n.","\r\n..",$html3);
                /// ------------------add  ? parapms mail
                //debug($html3);
                $html3=preg_replace('/href=\\"([^\\"]*?\\?[\\w\\W]*?)\\"/i', 'href="\1&frommail='.$receivers[$i][id].'"', $html3);
                $html3=preg_replace('/href=\\"([^\\?]*?)\\"/i', 'href="\1/?frommail='.$receivers[$i][id].'"', $html3);
                //debug($html3);
                /// --------------------------------------add QTY mail request !
                list($user,$id)=explode("|", $receivers[$i][id]);
                if ($user == "subscribe") 
                {
                    $db->exec("update subscribe set mail_request_qty=mail_request_qty+1 where id=$id");
                    $ins_id=$db->exec("insert into mail_statistics (id_grouping,mail_id,user_id,user_type,date) values ($max_id_grouping,$template_id,$id,'subscriber','$now')");
                }
                if ($user == "client") 
                {
                    $db->exec("update clients set mail_request_qty=mail_request_qty+1 where client_id=$id");
                    $ins_id=$db->exec("insert into mail_statistics (id_grouping,mail_id,user_id,user_type,date) values ($max_id_grouping,$template_id,$id,'client','$now')");
                }
                // for mail statistic by letter -------
                    $html3=preg_replace('/href=\\"([^\\"]*?\\?[\\w\\W]*?)\\"/i', 'href="\1&mstat='.$ins_id.'"', $html3);
                /// -------------------------------------- 
                $mail->Body     =  $html3;
                $mail->to=array();
                $mail->AddAddress($receivers[$i][email]);               // optional name
                $mail->Send();
            }
            $_SESSION["echo_result"]="<br>\nMessage has been sent to the receivers (Quantity=$i)";
                            
            header("location: ?".$this->getURL());
        }
        if ( "doDelete" == $_GET['action'])
        {
            $uid = $_GET['id'];
            if(empty($uid) || $uid<0 || !is_numeric($uid) )
            {
                header("location: ./?".$this->getURL());
                exit();
            }
            $core = getCoreInstance();
            $db = $core->getProperty("db");
            
            $sql = "delete from mail_templates where id=".str2db($uid)."";
            //$db->Exec($sql);
        }
        
        return true;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------
    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = getCoreInstance();
        $render = $core->framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";

        switch ($_G["page"]) {
            case "edit":
                $page = $this->renderNewsletterEdit($render);
                break;
            case "add":
                $page = $this->renderNewsletterAdd($render);
                break;
            case "send":
                $page = $this->renderNewsletterSend($render);
                break;
            case "statistic_l":
                $page = $this->renderMailStatistic_l($render);
                break;
            case "print_l":
                $page = $this->renderMailStatistic_l($render);
                break;
            case "statistic_u":
                $page = $this->renderMailStatistic_u($render);
                break;
            case "print_u":
                $page = $this->renderMailStatistic_u($render);
                break;
            case "statistic_u1":
                $page = $this->renderMailStatistic_u1($render);
                break;
            case "print_u1":
                $page = $this->renderMailStatistic_u1($render);
                break;
                        
            default:
                $page = $this->renderNewsletterList($render);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }


    // ----------------------------------------------------------------------------------
    // --- [ Newsletter List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------
    
    function cb_renderNewslist($data)
    {
        $dt = array(
                array($data["id"] , "align=\"center\""),
                array((strlen($data[template_name])>21 ? substr($data[template_name],0,19)."..." : $data[template_name]) , ""),
                array((strlen($data[subject])>21 ? substr($data[subject],0,19)."..." : $data[subject]) , ""),
                array(addslashes((strlen($data[content])>32 ? substr($data[content],0,30)."..." : $data[content])) , " "),
                array("<a href=\"?".$this->getURL()."&page=edit&id={$data[id]}\">edit</a>&nbsp;<a href=\"?".$this->getURL()."&action=doDelete&id={$data[id]}\">delete</a>" , "align=\"center\"")
                );
//      debug($dt, "CBfunction");
        return $dt;
    }

    function renderNewsletterList(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $pg = &$core->getSnippet("paginator");
//      debug($pg, get_class($pg));

        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_renderNewslist,
                    "urlbase" => $this->getURL(),
                    "caption" => "eMail Templates list",
                    "emptymsg" => "No email templates created yet",
                    "header" => array("ID", "Template Name","Subject" , "Content", "Actions"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select id, template_name, subject, content  from mail_templates",
                    "sql_count" => "select count(*) from mail_templates",
                    "ippg" => 10, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    );
        $HTML = $pg->Render($params);
        if (isset($_SESSION["echo_result"])) 
        {            
            $render->assign('echo_result',$_SESSION["echo_result"]);
            unset($_SESSION["echo_result"]);
        }
        $render->assign('add_url',$this->getURL());
        $render->assign('send_url',"?".$this->getURL()."&page=send" );
        $render->assign("customers", $HTML);

        return "newsletterlist.tpl.php";
    }
    
    
    // ----------------------------------------------------------------------------------
    // --- [ Generate Newsletter Edit ] --------------------------------------------------
    // ----------------------------------------------------------------------------------

    function renderNewsletterEdit(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $uid = $_GET["id"];
        if(empty($uid) || $uid<0 || !is_numeric($uid) )
        {
            header("location: ./?".$this->getURL());
            exit();
        }
        
        $render->assign("url", "?".$this->getURL());
        $render->assign("cancel_url", "?".$this->getURL());
        $render->assign("id", $uid);
        $render->assign("action", 'doSubmitSubscriber');
        
        $render->assign("item", $db->getRow("select * from mail_templates where id={$uid}"));
        
    //-------- fck editor        
        $sBasePath = "../lib/fckeditor/";
        $oFCKeditor = new FCKeditor('content') ;
        $oFCKeditor->BasePath   = $sBasePath ;
        $oFCKeditor->ToolbarSet = "Default"; // Optimum
        $oFCKeditor->Height     = 450;
        $oFCKeditor->Width      = 640;
        $oFCKeditor->Value      = db2str($db->getone("select content from mail_templates where id=$uid"));
        $html_editor=$oFCKeditor->CreateHtml();
        $render->assign("html_edit",$html_editor );
    //-------- /fck editor        
        
        return "newsletteredit.tpl.php";
    }
    // ----------------------------------------------------------------------------------
    // --- [ Generate Newsletter Add ] --------------------------------------------------
    // ----------------------------------------------------------------------------------

    function renderNewsletterAdd(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $render->assign("url", "?".$this->getURL());
        $render->assign("cancel_url", "?".$this->getURL());
        $render->assign("id", $uid);

        $render->assign("action", 'doAddNewsletter');
    //-------- fck editor       
        $sBasePath = "../lib/fckeditor/";
        $oFCKeditor = new FCKeditor('content') ;
        $oFCKeditor->BasePath   = $sBasePath ;
        $oFCKeditor->ToolbarSet = "Default"; // Optimum
        $oFCKeditor->Height     = 450;
        $oFCKeditor->Width      = 640;
        $oFCKeditor->Value      = "";
        $html_editor=$oFCKeditor->CreateHtml();
        $render->assign("html_edit",$html_editor );
    //-------- /fck editor        
        return "newsletteredit.tpl.php";
    }

    // ----------------------------------------------------------------------------------
    // --- [ Generate Newsletter Send ] --------------------------------------------------
    // ----------------------------------------------------------------------------------

    function renderNewsletterSend(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");

        $q="select id,template_name from mail_templates order by id asc";
        $templates = $db->getAll($q);
        $render->assign('templates',$templates);

        $q="select id, fname, lname from subscribe order by fname asc";
        $users = $db->getAll($q,0);
        
         $user_mas=array();
         $user_id=array();
        for ($i=0; $i<count($users); $i++)
        {
            $user_mas_item=$users[$i]["fname"]." ".$users[$i]["lname"];
            if ($user_mas_item!="") 
            $user_mas[]=$user_mas_item;
            else $user_mas[]="--- unknown ---";
            $user_id[]=$users[$i]["id"];
        }
        $render->assign('user_id',$user_id);
        $render->assign('user_mas',$user_mas);
        
        
        $clients=$db->getall("select client_id, client_name from clients where client_name != 'noone' and client_name != 'Administrator'");
        $render->assign('clients',$clients);
        
        $render->assign('mail_groups',$db->getall("select group_id, name from mail_groups"));
        
        $render->assign("cancel_url", "?".$this->getURL());     
        $render->assign("url", "?".$this->getURL()."&page=send" );
        
        //      $render->assign("url", "?".$this->getURL());

//      $render->assign("id", $uid);

        return "newslettersend.tpl.php";
    }
    
    function renderMailStatistic_l(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $stat_sql="select ms.id_grouping, ms.mail_id, mt.template_name, mt.subject, ms.date, ms.user_type, 
                                count(ms.id_grouping) as qty, sum(ms.has_come) as sum_visit, sum(ms.has_come_buy) as sum_buy  
                        from mail_statistics ms, mail_templates mt  
                        where ms.mail_id=mt.id 
                        group by ms.id_grouping
                        order by date desc";
        $stat=$db->getAll($stat_sql);
        $stat=arraydb2str($stat);
        for ($i=0;$i<count($users);$i++)
        {
            $mail_response_sum+=$users[$i][mail_response_qty];
        }
        $render->assign("stat", $stat);
        $render->assign("mail_response_sum", $mail_response_sum);
        $render->assign('add_url',$this->getURL());
        return "mailstatistic_l.tpl.php";
    }
    
    function renderMailStatistic_u(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $q_subscriber="select 'subscriber' as user, concat(fname,' ',lname) as name, count(ms.id_grouping) as qty,
                                    sum(ms.has_come) as sum_visit, sum(ms.has_come_buy) as sum_buy  
                            from subscribe left join mail_statistics ms on (subscribe.id = ms.user_id)
                            where user_type='subscriber'
                            group by subscribe.id";
        $q_client="select 'client' as user, client_name as name, count(ms.id_grouping) as qty,
                                sum(ms.has_come) as sum_visit, sum(ms.has_come_buy) as sum_buy  
                        from clients left join mail_statistics ms on (clients.client_id = ms.user_id)
                        where user_type='client' and client_name != 'noone' and client_name != 'Administrator' 
                        group by clients.client_id";
        $users=array_merge($db->getAll($q_subscriber,0),$db->getAll($q_client,0));
        /*
        select ms.id_grouping, ms.mail_id, mt.template_name, mt.subject, ms.date, concat(u.fname,' ',u.lname) as name, u.id as user_id, ms.user_type, sum(ms.has_come), sum(ms.has_come_buy)  
        from mail_statistics ms, subscribe u, mail_templates mt  
        where ms.mail_id=mt.id and ms.user_id=u.id and ms.user_type='subscriber' 
        group by ms.id_grouping
        */
        $users=arraydb2str($users);
        //debug($users);
        for ($i=0;$i<count($users);$i++)
        {
            $mail_response_sum+=$users[$i][mail_response_qty];
        }
                
        $render->assign("users", $users);
        $render->assign("mail_response_sum", $mail_response_sum);
        /*foreach ($rating_vendors as $v) $sum+=$v[sum_rating];
        if ($sum==0) $sum=1;
        $render->assign("rating_sum", $sum);*/
        $render->assign('add_url',$this->getURL());
        
        return "mailstatistic_u.tpl.php";
    }
    
    function renderMailStatistic_u1(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $q_subscriber="select 'subscriber' as user, concat(fname,' ',lname) as name, mail_response_qty, mail_request_qty from subscribe";
        $q_client="select 'client' as user, client_name as name, mail_response_qty, mail_request_qty from clients where client_name != 'noone' and client_name != 'Administrator'";
        $users=array_merge($db->getAll($q_subscriber,0),$db->getAll($q_client,0));
        /*
        select ms.id_grouping, ms.mail_id, mt.template_name, mt.subject, ms.date, concat(u.fname,' ',u.lname) as name, u.id as user_id, ms.user_type, sum(ms.has_come), sum(ms.has_come_buy)  
        from mail_statistics ms, subscribe u, mail_templates mt  
        where ms.mail_id=mt.id and ms.user_id=u.id and ms.user_type='subscriber' 
        group by ms.id_grouping
        */
        $users=arraydb2str($users);
        for ($i=0;$i<count($users);$i++)
        {
            $mail_response_sum+=$users[$i][mail_response_qty];
        }
                
        $render->assign("users", $users);
        $render->assign("mail_response_sum", $mail_response_sum);
        /*foreach ($rating_vendors as $v) $sum+=$v[sum_rating];
        if ($sum==0) $sum=1;
        $render->assign("rating_sum", $sum);*/
        $render->assign('add_url',$this->getURL());
        
        return "mailstatistic_u1.tpl.php";
    }
    
    //__________________________________________________________________________________
    ////////////////////////---------  PRINT ----------//////////////////////////////////////////////////////
    
    function Render_print_l(&$render)
    {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $stat_sql="select ms.id_grouping, ms.mail_id, mt.template_name, mt.subject, ms.date, ms.user_type, 
                                count(ms.id_grouping) as qty, sum(ms.has_come) as sum_visit, sum(ms.has_come_buy) as sum_buy  
                        from mail_statistics ms, mail_templates mt  
                        where ms.mail_id=mt.id 
                        group by ms.id_grouping
                        order by date desc";
        $stat=$db->getAll($stat_sql);
        $stat=arraydb2str($stat);
        for ($i=0;$i<count($users);$i++)
        {
            $mail_response_sum+=$users[$i][mail_response_qty];
        }
        $render->assign("stat", $stat);
        $render->assign("mail_response_sum", $mail_response_sum);
        $render->assign('add_url',$this->getURL());
        return "print_l.tpl.php";
    }
};


?>